package com.lyc.assistant.translate.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.lyc.assistant.R
import com.lyc.assistant.base.BaseActivity
import com.lyc.assistant.click.XClickUtil
import com.lyc.assistant.databinding.ActivityOfflineTranslateBinding
import com.lyc.assistant.translate.adapter.LanguagePackageAdapter
import com.translation.assistant.callback.OnModelListener
import com.translation.assistant.data.OfflineConstant
import com.translation.assistant.manager.OfflineTranslatorManager
import com.translation.assistant.utils.NetworkUtil
import java.util.*

@SuppressLint("NotifyDataSetChanged")
class OfflineTranslateActivity: BaseActivity<ActivityOfflineTranslateBinding>() {
    private lateinit var adapter: LanguagePackageAdapter
    private val downloadedModelList = ArrayList<String>()
    private val downloadMap = HashMap<String, String>()
    private lateinit var translator: OfflineTranslatorManager

    override fun getLayoutId(): Int {
        return R.layout.activity_offline_translate
    }

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        setStatusBarFontColor(false)
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_offline_translate)
        translator = OfflineTranslatorManager(this@OfflineTranslateActivity)
        mDataBinding.apply {
            layoutTitle.ivLeft.setOnClickListener { finish() }
            layoutTitle.tvTitle.text = "离线翻译"
        }

        setAdapter()
    }

    private fun setAdapter() {
        mDataBinding.recyclerView.layoutManager = LinearLayoutManager(this)
        mDataBinding.recyclerView.itemAnimator = DefaultItemAnimator()
        adapter = LanguagePackageAdapter(OfflineConstant.ALL_LANGUAGES, downloadedModelList, downloadMap)
        //adapter.setAnimationEnable(true);
        //adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom);
        //adapter.setAnimationEnable(true);
        //adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom);
        mDataBinding.recyclerView.adapter = adapter
        adapter.setOnItemChildClickListener(OnItemChildClickListener { adapter, view, position ->
            if (XClickUtil.isFastDoubleClick(view, XClickUtil.INTERVAL_MILLIS)) {
                return@OnItemChildClickListener
            }
            if (view.id == R.id.tv_download) {
                val tvDownload = view as TextView
                val languageCode: String = OfflineConstant.ALL_LANGUAGES[position].code
                if (tvDownload.text.toString() == "下载") {
                    checkNetworkAndDoNext(languageCode, tvDownload, position)
                } else if (tvDownload.text.toString() == "删除") {
                    //删除
                    deleteModel(languageCode, position)
                }
            } else if (view.id == R.id.rl_parent) {
                //
            }
        })
    }

    private fun checkNetworkAndDoNext(languageCode: String, tvDownload: TextView, position: Int) {
        when (NetworkUtil.checkNetwork(this@OfflineTranslateActivity)) {
            NetworkUtil.NETWORK_WIFI -> downloadModel(languageCode, tvDownload, position)
            NetworkUtil.NETWORK_MOBILE -> AlertDialog.Builder(this@OfflineTranslateActivity)
                .setTitle(R.string.prompt)
                .setMessage(R.string.no_wifi_prompt)
                .setPositiveButton(R.string.str_ok
                ) { dialog, which ->
                    downloadModel(languageCode,
                        tvDownload,
                        position)
                }.setNegativeButton(R.string.str_cancel
                ) { dialog, which ->

                }.create().show()
            else -> AlertDialog.Builder(this@OfflineTranslateActivity).setTitle(R.string.prompt)
                .setMessage(R.string.no_network_prompt)
                .setPositiveButton(R.string.str_ok
                ) { dialog, which ->

                }
                .setNegativeButton(R.string.str_cancel
                ) { dialog, which ->

                }.create().show()
        }
    }

    /**
     * 下载语种包
     */
    private fun downloadModel(languageCode: String, tvDownload: TextView, position: Int) {
        downloadMap[languageCode] = getString(R.string.waitting)
        mXHandler.post { adapter.notifyDataSetChanged() }

        //下载监听器
        val modelDownloadListener =  object : OnModelListener<Void>{
            override fun onSuccess(result: Void?) {
                downloadedModelList.add(languageCode)
                downloadMap.remove(languageCode)
                mXHandler.post { adapter.notifyDataSetChanged() }
            }

            override fun onFailure(var1: Exception?) {
                downloadMap.remove(languageCode)
                mXHandler.post { adapter.notifyDataSetChanged() }
                Toast.makeText(this@OfflineTranslateActivity, var1?.message, Toast.LENGTH_SHORT).show()
            }

            override fun onProcess(var1: Long, var2: Long) {
                showProcess(languageCode, var1, var2, position)
            }

        }
        translator.downloadModel(languageCode,modelDownloadListener)

    }

    private fun deleteModel(languageCode: String, position: Int) {
        //监听器
        val modelDeleteListener =  object : OnModelListener<Void>{
            override fun onSuccess(result: Void?) {
                downloadedModelList.remove(languageCode)
                adapter.notifyDataSetChanged()
            }

            override fun onFailure(var1: Exception?) {
                adapter.notifyDataSetChanged()
            }

            override fun onProcess(var1: Long, var2: Long) {
            }

        }
        translator.deleteModel(languageCode,modelDeleteListener)
    }

    private fun showProcess(
        languageCode: String,
        alreadyDownLength: Long,
        totalLength: Long,
        position: Int,
    ) {
        /*double downDone = alreadyDownLength * 1.0 / OfflineConstant.M;
        double downTotal = totalLength * 1.0 / OfflineConstant.M;
        String downD = String.format(Locale.ROOT,"%.2f", downDone);
        String downT = String.format(Locale.ROOT,"%.2f", downTotal);

        String text = downD + "M" + "/" + downT + "M";*/
        val text = String.format(Locale.ROOT, "下载%2d%s", alreadyDownLength * 100 / totalLength, "%")
        downloadMap[languageCode] = text
        mXHandler.post { adapter.notifyDataSetChanged() }
    }
}